<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>杭银消金机器人</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }

        .chat-container {
            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow: hidden;
        }

        .chat-header {
            background-color: #4CAF50;
            color: white;
            padding: 10px;
            text-align: center;
        }

        .chat-body {
            overflow-y: scroll; /* 保持滚动 */
            padding: 10px;
            flex: 1;
        }

        .message {
            margin-bottom: 10px;
        }

        .message.user {
            text-align: right;
        }

        .message.bot {
            text-align: left;
        }

        .message-text {
            background-color: #e5e5ea;
            padding: 8px;
            border-radius: 8px;
            display: inline-block;
            max-width: 70%;
        }

        .message-text.bot {
            background-color: #4CAF50;
            color: white;
        }

        .input-container {
            display: flex;
            padding: 10px;
            background-color: white;
            position: sticky;
            bottom: 0;
            width: 100%;
            margin-top: auto; /* 确保输入框贴着底部显示 */
        }

        .message-input {
            flex: 1;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        .send-button {
            padding: 8px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-left: 5px; /* 调整左边的间距 */
            margin-right: 10px;
        }
    </style>
</head>
<body>

<div class="chat-container">
    <div class="chat-header">客服机器人</div>
    <div class="chat-body" id="chatBody">
        <!-- 聊天消息将在此显示 -->
    </div>
    <div class="input-container">
        <input type="text" id="messageInput" class="message-input" placeholder="输入问题...">
        <button onclick="sendMessage()" class="send-button">发送</button>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
    const queryString = window.location.search;
    const searchParams = new URLSearchParams(queryString);
    const params = Object.fromEntries(searchParams.entries());
    const accountNo = params.accountNo;
    let systemMsg;
    // 使用 $.get() 发起 GET 请求
    $.get("http://127.0.0.1:8080/rest/myservice/v1/get?accountNo=" + accountNo, function (data) {
        systemMsg = data;
    }).fail(function () {
            // 请求失败时的处理
            console.error("Error making GET request");
        });

    function sendMessage() {
        const messageInput = document.getElementById('messageInput');
        const chatBody = document.getElementById('chatBody');

        const userMessage = messageInput.value.trim();
        if (userMessage !== '') {
            // 用户消息
            const userMessageDiv = document.createElement('div');
            userMessageDiv.className = 'message user';
            const userMessageTextDiv = document.createElement('div');
            userMessageTextDiv.className = 'message-text';
            userMessageTextDiv.textContent = userMessage;
            userMessageDiv.appendChild(userMessageTextDiv);
            chatBody.appendChild(userMessageDiv);
            simulateBotResponse(userMessage);
            // 清空输入框
            messageInput.value = '';

            // 滚动到底部
            chatBody.scrollTop = chatBody.scrollHeight;
        }
    }

    function simulateBotResponse(userMessage) {
        // 机器人消息
        const botMessageDiv = document.createElement('div');
        botMessageDiv.className = 'message bot';
        const botMessageTextDiv = document.createElement('div');
        botMessageTextDiv.className = 'message-text bot';
        botMessageDiv.appendChild(botMessageTextDiv);
        chatBody.appendChild(botMessageDiv);

        const eventSourceUrl = 'http://localhost:8885/app/chat/chat?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMDUiLCJpYXQiOjE3MDIyODIyODgsImV4cCI6MTcwMjg4NzA4OH0.g16lQKGubmvnm963DJbow5P7a-Og4Qg9hbEOH_QFLL-CnqOXG6kylTih8lcdus_7dQBG5yptz0vHZQQu0GWAfg';
        const postData = {prompt: userMessage, systemMsg: systemMsg, userNo: accountNo};
        fetch(eventSourceUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            timeout: 100000,
            body: JSON.stringify(postData),
        })
            .then(response => response.body)
            .then(body => {
                // 处理成功的响应
                console.log(body);
                const reader = body.getReader();

                // 处理 SSE 事件流
                function processSseEvent(event) {
                    console.log('Received data:', event.data);
                    //2个代表换行
                    const eventData = event.data.replace(/^data:data:\s*/, '\/n');
                    // 去除 "data:" 前缀
                    const eventData2 = eventData.replace(/^data:\s*/, '');
                    // 在这里处理接收到的数据，更新界面或执行其他操作
                    botMessageTextDiv.textContent += eventData2;
                }

                // 处理 SSE 数据流
                function readStream() {
                    return reader.read().then(({done, value}) => {
                        if (done) {
                            console.log('SSE stream closed');
                            return;
                        }
                        // 将 ArrayBuffer 转换为文本
                        const text = new TextDecoder().decode(value);

                        // 将文本分割为多个 SSE 事件
                        const events = text.split('\n\n');

                        // 处理每个事件
                        events.forEach(event => {
                            const sseEvent = new Event('message');
                            sseEvent.data = event;
                            processSseEvent(sseEvent);
                        });
                        // 继续读取下一个数据块
                        readStream();
                    });
                }

                // 启动 SSE 数据流读取
                readStream();
            })
            .catch(error => {
                // 处理错误
                console.error('Error making POST request:', error);
            });
    }
</script>

</body>
</html>
